package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicUserInfo;
import com.bzkj.basicinfo.domain.ncc.erp.UserInfoRootBean;
import com.bzkj.basicinfo.mapper.NccBasicManufacturerInfoMapper;
import com.bzkj.basicinfo.mapper.NccBasicUserInfoMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicUserInfoService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 人员信息：5
 */
@Service("nccJobUserInfoService")
@Slf4j
public class NccBasicUserInfoServiceImpl implements NccBasicUserInfoService {
    @Autowired
    private NccBasicUserInfoMapper nccBasicUserInfoMapper;

    @Autowired
    private NccBasicManufacturerInfoMapper nccBasicManufacturerInfoMapper;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Autowired
    private HttpClientUtils hcu;

    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private String url;

    @Value("${ncc.basicInfoUrl}")
    private String basicInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;


    @Override
    public void updateNccBasicUserInfoJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(5, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(5);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicUserInfo> basicUserInfos = dataArray.toList(NccBasicUserInfo.class);
                for (NccBasicUserInfo basicUserInfo : basicUserInfos) {
                    NccBasicUserInfo basicCustomer1 = nccBasicUserInfoMapper.queryNccBasicUserInfo(basicUserInfo.getCode());
                    if (basicCustomer1 != null) {
                        nccBasicUserInfoMapper.updateNccBasicUserInfo(basicUserInfo);
                    } else {
                        nccBasicUserInfoMapper.insertNccBasicUserInfo(basicUserInfo);
                    }
                }
            }
        }
    }

    /**
     * 新增人员信息
     *
     * @param entity
     * @Author wangzhichao
     * @Date 2024/12/04 14:56:57
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult nccBasicUserInfoSave(NccBasicUserInfo entity) {
        try {
            NccBasicUserInfo one = nccBasicUserInfoMapper.findUserCodeIsExist(entity.getCode());
            if (Objects.isNull(one)) {
                // 生成唯一erp用户id
                synchronized (this) {
                    String userRedId = "WMS" + uniq.generateUniqueIdentifier();
                    entity.setpK_PSNDOC(userRedId);
                }
                nccBasicUserInfoMapper.insertNccBasicUserInfo(entity);
                return AjaxResult.success("新增成功");
            } else {
                return AjaxResult.error("员工已经存在");
            }
        } catch (Exception e) {
            throw new RuntimeException("新增人员信息失败:", e);
        }

    }

    /**
     * 修改人员状态
     *
     * @param status    状态
     * @param pK_PSNDOC 编号
     * @Author wangzhichao
     * @Date 2024/12/04 14:57:10
     */
    @Override
    public AjaxResult nccBasicUserInfoEnableStateUpdate(String status, String pK_PSNDOC) {
        try {
            int i = nccBasicUserInfoMapper.nccBasicUserInfoEnableStateUpdate(status, pK_PSNDOC);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定人员信息");
        } catch (Exception e) {
            log.error("修改失败：" + e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 修改人员信息
     *
     * @Author wangzhichao
     * @Date 2024/12/04 15:13:53
     * @Param entity 要修改的数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult nccBasicUserInfoUpdate(NccBasicUserInfo entity) {
        try {
            NccBasicUserInfo nccBasicUserInfo = nccBasicUserInfoMapper.findUserCodeIsExist(entity.getCode());
            if (Objects.isNull(nccBasicUserInfo)) {
                int i = nccBasicUserInfoMapper.nccBasicUserInfoUpdate(entity);
                return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定人员信息");
            } else {
                if ((nccBasicUserInfo.getpK_PSNDOC().equals(entity.getpK_PSNDOC())) && (nccBasicUserInfo.getCode().equals(entity.getCode()))) {
                    nccBasicUserInfoMapper.nccBasicUserInfoUpdate(entity);
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("人员代码重复");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("人员信息修改失败:" + e);
        }
    }

    /**
     * 分页查询人员信息
     *
     * @param entity 查询条件
     * @Author wangzhichao
     * @Date 2024/12/04 16:52:40
     */
    @Override
    public List<NccBasicUserInfo> nccBasicUserInfoFindList(NccBasicUserInfo entity) {
        return nccBasicUserInfoMapper.nccBasicUserInfoFindList(entity);
    }

    @Override
    public List<String> findNccBasicUserNameList(String userName) {
        return nccBasicUserInfoMapper.findNccBasicUserNameList(userName);
    }

    @Override
    public String findNccBasicByUserRefId(String userRefId) {
        return nccBasicUserInfoMapper.findNccBasicUserRefId(userRefId);
    }

    /**
     * 定时同步当天人员信息
     *
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 5, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<UserInfoRootBean> list = jsonNode.getJSONArray("data").toJavaList(UserInfoRootBean.class);
        if (!list.isEmpty()){
            extracted(list);
        }
        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<UserInfoRootBean> list) {
        for (UserInfoRootBean userInfoRootBean : list) {
            nccBasicUserInfoMapper.insertOrUpdate(userInfoRootBean);
        }
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i) {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }
}
